package cs5226.tags;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class DbResultSetHeader extends SimpleTagSupport {
	public final String TH_OPENING = "<th class='TableHeader'>";
	public final String TH_CLOSING = "</th>";
	
	private ResultSet resultset;

	@Override
	public void doTag() throws JspException, IOException {
		if (resultset == null) {
			getJspContext().getOut().println(TH_OPENING + "No result set found" + TH_CLOSING);
			return;
		}

		try {
			ResultSetMetaData metadata = resultset.getMetaData();
			int columnCount = metadata.getColumnCount();

			JspWriter out = getJspContext().getOut();
			out.println("<tr>");

			for (int i = 0; i < columnCount; i++) {
				String columnName = metadata.getColumnName(i + 1);
				out.println(TH_OPENING + columnName + TH_CLOSING);
			}

			out.println("<tr>");

		} catch (SQLException e) {
			e.printStackTrace();
			getJspContext().getOut().println(
					TH_CLOSING + "Exception: " + e.getMessage() + TH_CLOSING);
		}

	}

	public ResultSet getResultset() {
		return resultset;
	}

	public void setResultset(Object value) {
		System.out.println ("============ Result set: " + value);
		if (value instanceof java.sql.ResultSet) {
			this.resultset = (ResultSet) value;
		}
		else this.resultset = null;
	}

}
